﻿using System;
using System.Collections.Generic;
using System.Text;
using Kugar.Core.Configuration;
using Kugar.Core.ExtMethod;
using Kugar.Tool.MongoDBHelper;
using MongoDB.Bson;
using Newtonsoft.Json.Linq;

namespace Kugar.Tools.CityToolUpdater
{
    public class MongoDBExecutor : IExecutor
    {
        private IMongoDBContext _helper = null;

        public MongoDBExecutor(string conn)
        {
            _helper = new MongoDBContextHelper(conn, "");

        }

        public void Execute(JArray data)
        {
            var type = CustomConfigManager.Default["Config:Table:Type"].ToInt();

            if (type == 0) //单容器
            {
                singleCol(data);
            }
            else
            {
                mutilCol(data);
            }
        }

        private void singleCol(JArray data)
        {
            var tablename = CustomConfigManager.Default["Config:Table:Name"].IfEmptyOrWhileSpace("base_City");

            var cityCol = _helper.GetCollection(tablename);

            foreach (JObject province in data)
            {
                var provinceid = ObjectId.GenerateNewId();

                cityCol.Insert(new BsonDocument()
                {
                    ["_id"] = provinceid,
                    ["Type"] = 0,
                    ["Name"] = province.GetString("name"),
                    ["ShortName"] = province.GetString("shortname"),
                    ["Code"] = province.GetString("code").ToInt(),
                    ["ParentID"] = ObjectId.Empty,
                    ["ParentCode"] = -1,
                    ["FullPathName"] = province.GetString("name"),
                    ["Code_Path"] = new BsonArray()
                                  {
                                      province.GetString("code").ToInt()
                                  },
                    ["Code_PathStr"] = province.GetString("code")
                });

                Console.WriteLine($"正在插入:{province.GetString("name")}");

                var citylist = province.GetJObjectArray("sub");

                foreach (var city in citylist)
                {
                    var cityid = ObjectId.GenerateNewId();

                    cityCol.Insert(new BsonDocument()
                    {
                        ["_id"] = cityid,
                        ["Type"] = 1,
                        ["Name"] = city.GetString("name"),
                        ["ShortName"] = province.GetString("shortname"),
                        ["Code"] = city.GetString("code").ToInt(),
                        ["ParentID"] = provinceid,
                        ["ParentCode"] = province.GetString("code").ToInt(),
                        ["Code_Path"] = new BsonArray(new[]
                                                     {
                                                        province.GetString("code").ToInt(),
                                                        city.GetString("code").ToInt()
                                                     }),
                        ["FullPathName"] = (province.GetString("name") == city.GetString("name")) ? city.GetString("name") : $"{province.GetString("name")}{city.GetString("name")}",
                        ["Code_PathStr"] = province.GetString("code") + "_" + city.GetString("code")
                    });

                    Console.WriteLine($"正在插入:{province.GetString("name")}-{city.GetString("name")}");

                    foreach (var district in city.GetJObjectArray("sub"))
                    {
                        var distractid = ObjectId.GenerateNewId();

                        var parentFullName = (province.GetString("name") == city.GetString("name"))
                            ? city.GetString("name")
                            : $"{province.GetString("name")}{city.GetString("name")}";

                        cityCol.Insert(new BsonDocument()
                        {
                            ["_id"] = distractid,
                            ["Type"] = 2,
                            ["Name"] = district.GetString("name"),
                            ["ShortName"] = province.GetString("shortname"),
                            ["Code"] = district.GetString("code").ToInt(),
                            ["ParentID"] = cityid,
                            ["ParentCode"] = city.GetString("code").ToInt(),
                            ["Code_Path"] = new BsonArray(new[]
                                                                         {
                                                                             province.GetString("code").ToInt(),
                                                                             city.GetString("code").ToInt(),
                                                                             district.GetString("code").ToInt()
                                                                         }),
                            ["FullPathName"] = $"{parentFullName}{district.GetString("name")}",
                            ["Code_PathStr"] = province.GetString("code") + "_" + city.GetString("code") + "_" + district.GetString("code")
                        });

                        Console.WriteLine($"正在插入:{province.GetString("name")}-{city.GetString("name")}-{district.GetString("name")}");
                    }
                }
            }
        }

        private void mutilCol(JArray data)
        {
            var citytablename = CustomConfigManager.Default["Config:Table:City"].IfEmptyOrWhileSpace("base_City");
            var provincetablename = CustomConfigManager.Default["Config:Table:Province"]
                .IfEmptyOrWhileSpace("base_Province");
            var districttablename = CustomConfigManager.Default["Config:Table:District"].IfEmptyOrWhileSpace("base_District");

            var provinceCol = _helper.GetCollection(provincetablename);
            var cityCol = _helper.GetCollection(citytablename);
            var districtCol = _helper.GetCollection(districttablename);

            foreach (JObject province in data)
            {
                var provinceid = ObjectId.GenerateNewId();

                provinceCol.Insert(new BsonDocument()
                {
                    ["_id"] = provinceid,
                    ["ProvinceName"] = province.GetString("name"),
                    ["ProvinceCode"] = province.GetString("code").ToInt()
                });

                Console.WriteLine($"正在插入:{province.GetString("name")}");

                var citylist = province.GetJObjectArray("sub");

                foreach (var city in citylist)
                {
                    var cityid = ObjectId.GenerateNewId();

                    cityCol.Insert(new BsonDocument()
                    {
                        ["_id"] = cityid,
                        ["Name"] = city.GetString("name"),
                        ["Code"] = city.GetString("code").ToInt(),
                        ["ProvinceID"] = provinceid,
                        ["ProvinceCode"] = province.GetString("code").ToInt(),
                        ["Code_Path"] = new BsonArray(new[]
                                                     {
                                                        province.GetString("code").ToInt(),
                                                        city.GetString("code").ToInt()
                                                     })
                    });

                    Console.WriteLine($"正在插入:{province.GetString("name")}-{city.GetString("name")}");

                    foreach (var district in city.GetJObjectArray("sub"))
                    {
                        var distractid = ObjectId.GenerateNewId();

                        districtCol.Insert(new BsonDocument()
                        {
                            ["_id"] = distractid,
                            ["Name"] = district.GetString("name"),
                            ["Code"] = district.GetString("code").ToInt(),
                            ["CityID"] = cityid,
                            ["CityCode"] = city.GetString("code").ToInt(),
                            ["Code_Path"] = new BsonArray(new[]
                                                                             {
                                                                                 province.GetString("code").ToInt(),
                                                                                 city.GetString("code").ToInt(),
                                                                                 district.GetString("code").ToInt()
                                                                             })
                        });

                        Console.WriteLine($"正在插入:{province.GetString("name")}-{city.GetString("name")}-{city.GetString("name")}");
                    }
                }
            }
        }
    }
}
